/**
 * Created by ren on 2016/12/13.
 */

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (event) {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            var data = JSON.parse(xhr.response);
            if (data.code === 1) {
                WebIM.config.address = data.object;
            }
        }
    }
};
xhr.open('get', WebIM.config.projectUrl+'/fancheng/api/oaOperator/findOASercerUrl', true);
xhr.send();

module.exports={
    login:function (username,password,callback) {
        var xhr1 = new XMLHttpRequest();
        xhr1.onreadystatechange = function (event) {
            if (xhr1.readyState == 4) {
                if (xhr1.status == 200) {
                    if(xhr1.response.indexOf('DOCTYPE')>-1){
                        callback(false);
                    }else{
                        var data = JSON.parse(xhr1.response);
                        var user = data.data;
                        WebIM.config.userId = user.notesid;
                        var xhr2 = new XMLHttpRequest();
                        xhr2.onreadystatechange = function (event) {
                            if (xhr2.readyState == 4) {
                                if (xhr2.status == 200) {
                                    data = JSON.parse(xhr2.response);
                                    WebIM.config.customData = data.data;
                                    callback(user);
                                }
                            }
                        };
                        xhr2.open('get', WebIM.config.address + '/fenchem/ems/si.nsf/app/get/persons?openagent&userId=' + WebIM.config.userId + '&end=10000', true);
                        xhr2.send();
                    }

                }
            }
        };
        xhr1.open('get', WebIM.config.address + '/names.nsf?login&redirectto=' + WebIM.config.address + '/fenchem/ems/si.nsf/app/get/user/profile?openagent&username='+username+'&password='+password+'', true);
        xhr1.send();
    },
    getUserPhoto:function (userId,callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function (event) {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var data = JSON.parse(xhr.response);
                    if (data.code === 1) {
                        if(data.object){
                            var userPhoto = WebIM.config.projectUrl+'/fancheng' + data.object.photo;
                            callback(userPhoto);
                        }else{
                            callback(false);
                        }
                    }
                }
            }
        };
        xhr.open('post', WebIM.config.projectUrl+'/fancheng/api/userPhoto/findUserPhoto?userId=' + userId, true);
        xhr.send();
    }
}